<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="所属栏目" prop="categoryId">
                <el-cascader
                    v-model="queryParams.categoryId"
                    placeholder="请选择所属栏目"
                    :options="categoryOptions"
                    :props="{ 
                        value: 'id', 
                        label: 'categoryTitle', 
                        children: 'children', 
                        checkStrictly: true,
                        emitPath: true,
                        expandTrigger: 'click',
                        checkStrictly: true
                    }"
                    clearable
                    @change="handleCategoryChange"
                    @visible-change="handleVisibleChange"
                    popper-class="category-cascader"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="文章标题" prop="contentTitle">
                <el-input
                        v-model="queryParams.contentTitle"
                        placeholder="请输入文章标题"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="显示状态" prop="contentDisplay">
                <el-select v-model="queryParams.contentDisplay" placeholder="请选择显示状态" clearable @change="handleQuery">
                    <el-option label="不显示" value="0"></el-option>
                    <el-option label="显示" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="删除标记" prop="del">
                <el-select v-model="queryParams.del" placeholder="请选择删除标记" clearable @change="handleQuery">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="已删除" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['cms:content:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['cms:content:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDeleteBatch"
                        v-hasPermi="['cms:content:remove']"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
                    <!-- <el-table-column label="${comment}" align="center" prop="id"/> -->
                    <el-table-column label="所属栏目" align="center" prop="categoryId">
                        <template slot-scope="scope">
                            <span>{{ getParentCategoryName(scope.row.categoryId) }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="文章内容" align="center" prop="contentDetails"/> -->
                    <el-table-column label="文章标题" align="center" prop="contentTitle">
                        <template slot-scope="scope">
                            <div>
                                <i class="el-icon-view" style="color: #409EFF;margin-right: 5px;"></i>
                                <span style="font-weight: bold;margin-right: 10px;">{{ scope.row.contentHit || 0 }}</span>
                                <span>{{ scope.row.contentTitle }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="文章副标题" align="center" prop="contentShortTitle"/> -->
                    <!-- <el-table-column label="关键字" align="center" prop="contentKeyword"/> -->
                    <!-- <el-table-column label="描述" align="center" prop="contentDescription"/> -->
                    <el-table-column label="文章缩略图" align="center" prop="contentImg">
                        <template slot-scope="scope">
                            <el-image 
                                :src="scope.row.contentImg" 
                                :preview-src-list="[scope.row.contentImg]"
                                fit="cover"
                                style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
                                lazy
                            >
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="文章来源" align="center" prop="contentSource"/> -->
                    <!-- <el-table-column label="文章作者" align="center" prop="contentAuthor"/> -->
                    <el-table-column label="显示状态" align="center" prop="contentDisplay">
                        <template slot-scope="scope">
                            <span>{{ scope.row.contentDisplay === '1' ? '显示' : '不显示' }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="文章类型" align="center" prop="contentType"/> -->
                    <!-- <el-table-column label="自定义顺序" align="center" prop="contentSort"/> -->
                    <!-- <el-table-column label="文章标签" align="center" prop="contentTags"/> -->
                    <!-- <el-table-column label="创建时间" align="center" prop="contentDatetime" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.contentDatetime) }}</span>
                        </template>
                    </el-table-column> -->
                    <!-- <el-table-column label="点击次数" align="center" prop="contentHit"/> -->
                    
                    
                    <el-table-column label="修改时间" align="center" prop="updateDate" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.updateDate) }}</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="创建时间" align="center" prop="createDate" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createDate) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="删除标记" align="center" prop="del">
                        <template slot-scope="scope">
                            <span>{{ scope.row.del === 1 ? '已删除' : '正常' }}</span>
                        </template>
                    </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['cms:content:edit']"
                    >修改
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['cms:content:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />

    </div>
</template>

<script>
import { getContent, listContent,batchDelContent,delContent } from "@/api/cms/content"
import { listAllCategory, listTreeCategory } from "@/api/cms/category"
import ContentEdit from "./editPage"

export default {
    name: "Content",
    components: { ContentEdit },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 文章表格数据
            contentList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 分类树形选项
            categoryOptions: [],
            // 分类ID到名称的映射
            categoryMap: {},
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                categoryId: null,
                contentDetails: null,
                contentTitle: null,
                contentShortTitle: null,
                contentKeyword: null,
                contentDescription: null,
                contentImg: null,
                contentSource: null,
                contentAuthor: null,
                contentDisplay: null,
                contentType: null,
                contentSort: null,
                contentTags: null,
                contentDatetime: null,
                contentHit: null,
                contentOutLink: null,
                hasDetailHtml: null,
                updateDate: null,
                hasListHtml: null,
                createDate: null,
                del: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            }
        }
    },
    created() {
        this.getList()
        this.getCategoryTree()
        this.getAllCategory()
    },
    methods: {
        /** 查询文章列表 */
        getList() {
            this.loading = true
            // 处理查询参数中的级联选择器值
            const queryParams = { ...this.queryParams }
            // 如果categoryId是数组，只取最后一级ID
            if (Array.isArray(queryParams.categoryId) && queryParams.categoryId.length > 0) {
                queryParams.categoryId = queryParams.categoryId[queryParams.categoryId.length - 1]
            }
            
            listContent(queryParams).then(response => {
                this.contentList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                categoryId: null,
                contentDetails: null,
                contentTitle: null,
                contentShortTitle: null,
                contentKeyword: null,
                contentDescription: null,
                contentImg: null,
                contentSource: null,
                contentAuthor: null,
                contentDisplay: null,
                contentType: null,
                contentSort: null,
                contentTags: null,
                contentDatetime: null,
                contentHit: null,
                contentOutLink: null,
                hasDetailHtml: null,
                updateDate: null,
                hasListHtml: null,
                updateBy: null,
                createDate: null,
                createBy: null,
                del: null
            }
            this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            // 重置查询参数中的categoryId为null
            this.queryParams.categoryId = null
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.$router.push("/cms/content/add");
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            const id = row.id || this.ids[0];
            if (id) {
                this.$router.push(`/cms/content/edit/${id}`);
            }
        },
        /** 提交按钮 */
        submitForm() {
            if (!this.$refs["form"]) {
                console.error('表单引用不存在')
                return
            }
            
            this.$refs["form"].validate(valid => {
                if (valid) {
                    try {
                        // 处理级联选择器的值，只取最后一级ID
                        const submitForm = { ...this.form }
                        if (Array.isArray(submitForm.categoryId) && submitForm.categoryId.length > 0) {
                            submitForm.categoryId = submitForm.categoryId[submitForm.categoryId.length - 1]
                        }else{
                            submitForm.categoryId = null
                        }
                        
                        if (submitForm.id != undefined) {
                            updateContent(submitForm).then(response => {
                                if (this.$modal && this.$modal.msgSuccess) {
                                    this.$modal.msgSuccess("修改成功")
                                } else {
                                    console.log("修改成功")
                                }
                                this.open = false
                                this.getList()
                            }).catch(error => {
                                console.error('修改失败:', error)
                            })
                        }
                        else {
                            addContent(submitForm).then(response => {
                                if (this.$modal && this.$modal.msgSuccess) {
                                    this.$modal.msgSuccess("新增成功")
                                } else {
                                    console.log("新增成功")
                                }
                                this.open = false
                                this.getList()
                            }).catch(error => {
                                console.error('新增失败:', error)
                            })
                        }
                    } catch (error) {
                        console.error('提交表单时出错:', error)
                    }
                }
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            try {
                if (this.$modal && this.$modal.confirm) {
                    this.$modal.confirm('是否确认删除名称为"' + (row.categoryTitle || '未命名') + '"的数据项？').then(() => {
                        return delContent(row.id)
                    }).then(() => {
                        this.getList()
                        if (this.$modal && this.$modal.msgSuccess) {
                            this.$modal.msgSuccess("删除成功")
                        } else {
                            console.log("删除成功")
                        }
                    }).catch(error => {
                        console.error('删除失败:', error)
                    })
                } else {
                    // 降级处理
                    if (confirm('是否确认删除名称为"' + (row.categoryTitle || '未命名') + '"的数据项？')) {
                        delContent(row.id).then(() => {
                            this.getList()
                            console.log("删除成功")
                        }).catch(error => {
                            console.error('删除失败:', error)
                        })
                    }
                }
            } catch (error) {
                console.error('删除操作出错:', error)
            }
        },
        
        /** 获取分类树形结构 */
        getCategoryTree() {
            // 尝试从API获取数据
            try {
                listTreeCategory().then(response => {
                    try {
                        // 处理树形数据，确保格式正确
                        const data = response && response.data ? response.data : []
                        this.categoryOptions = data
                    } catch (err) {
                        console.error('处理树形数据失败:', err)
                    }
                }).catch(error => {
                    console.error('获取分类树失败:', error)
                })
            } catch (error) {
                console.error('调用API失败:', error)
            }
        },
        
        /** 栏目选择变化时自动查询 */
        handleCategoryChange() {
            this.handleQuery()
        },
        
        /** 处理级联选择器显示/隐藏时的逻辑 */
        handleVisibleChange(visible) {
            // 确保组件正常显示和交互
            if (!visible && this.queryParams.categoryId) {
                // 当选择器关闭且有值时，确保查询正确执行
                this.handleQuery()
            }
        },
        
        /** 获取所有分类列表并构建ID到名称的映射 */
        getAllCategory() {
            listAllCategory({}).then(response => {
                const data = response.data || []
                // 构建ID到名称的映射
                this.categoryMap = {}
                if (Array.isArray(data)) {
                    data.forEach(item => {
                        // 确保有必要的属性
                        if (item.id && item.categoryTitle) {
                            this.categoryMap[item.id] = item.categoryTitle
                        }
                    })
                }
            }).catch(error => {
                console.error('获取所有分类列表失败:', error)
                // 出错时使用空映射
                this.categoryMap = {}
            })
        },
        
        /** 根据ID获取父级分类名称 - 使用Map快速查找 */
        getParentCategoryName(id) {
            if (!id || id === 0) {
                return '顶级分类';
            }
            
            // 从categoryMap中直接查找
            return this.categoryMap[id] || '未知分类';
        },

        handleDeleteBatch() {
            // 批量删除
            const ids = this.ids
            this.$modal.confirm('是否确认删除选中的数据项？').then(() => {
                // 使用优化后的delAction接口，直接传入id数组进行批量删除
                return batchDelContent(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => {
                this.$modal.msgError("删除失败")
            })
        },
    }
}
</script>

<style scoped>
.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
}
</style>
